package io.finer.erp.jeecg.finance.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasSupplier;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IBasSupplierService;
import io.finer.erp.jeecg.finance.entity.FinaNvoice;
import io.finer.erp.jeecg.finance.entity.TaxRate;
import io.finer.erp.jeecg.finance.mapper.FinaNvoiceMapper;
import io.finer.erp.jeecg.finance.service.IFinaNvoiceService;
import io.finer.erp.jeecg.finance.service.ITaxRateService;
import io.finer.erp.jeecg.finance.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 发票表单
 * @Author: jeecg-boot
 * @Date:   2021-03-23
 * @Version: V1.0
 */
@Api(tags="发票表单")
@RestController
@RequestMapping("/finance/finaNvoice")
@Slf4j
public class FinaNvoiceController extends JeecgController<FinaNvoice, IFinaNvoiceService> {
	@Autowired
	private IFinaNvoiceService finaNvoiceService;
	@Autowired
	private IBasCustomerService customerService;
	@Autowired
	private IBasSupplierService supplierService;
	@Autowired
	private ITaxRateService taxRateService;
	@Autowired
	private ISysBaseAPI baseAPI;
	@Autowired
	private FinaNvoiceMapper finaNvoiceMapper;

	 /**
	 * 分页列表查询
	 *
	 * @param finaNvoice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "发票表单-分页列表查询")
	@ApiOperation(value="发票表单-分页列表查询", notes="发票表单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FinaNvoice finaNvoice,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FinaNvoice> queryWrapper = QueryGenerator.initQueryWrapper(finaNvoice, req.getParameterMap());
		Page<FinaNvoice> page = new Page<FinaNvoice>(pageNo, pageSize);
		IPage<FinaNvoice> pageList = finaNvoiceService.page(page, queryWrapper);
		return Result.ok(pageList);
	}


	 /**
	  * 分页列表查询
	  *
	  * @param finaNvoice
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "付款发票表单-付款发票分页列表查询")
	 @ApiOperation(value="付款发票表单-付款发票分页列表查询", notes="付款发票表单-付款发票分页列表查询")
	 @GetMapping(value = "/listFK")
	 public Result<?> queryPageFKList(FinaNvoice finaNvoice,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<FinaNvoice> queryWrapper = QueryGenerator.initQueryWrapper(finaNvoice, req.getParameterMap());
		 Page<FinaNvoice> page = new Page<FinaNvoice>(pageNo, pageSize);
		 queryWrapper.eq("type","0");
		 IPage<FinaNvoice> pageList = finaNvoiceService.page(page, queryWrapper);
		 for (FinaNvoice record : pageList.getRecords()) {
		 	//获取税率
			String[] str=record.getTaxRate().split("%");
			//计算税额
			BigDecimal tax=new BigDecimal(str[0]).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
			BigDecimal taxAmount=record.getInvoicePrice().multiply(tax);
			record.setTaxAmount(taxAmount);//税额
			record.setNoTaxPrice(record.getInvoicePrice().subtract(taxAmount));//无税金额
			record.setTaxPrice(record.getInvoicePrice());//含税金额
		 }
		 return Result.ok(pageList);
	 }


	 /**
	  * 分页列表查询
	  *
	  * @param finaNvoice
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "收款发票表单-收款发票分页列表查询")
	 @ApiOperation(value="收款发票-收款发票分页列表查询", notes="收款发票-收款发票分页列表查询")
	 @GetMapping(value = "/listSK")
	 public Result<?> queryPageSKList(FinaNvoice finaNvoice,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		 QueryWrapper<FinaNvoice> queryWrapper = QueryGenerator.initQueryWrapper(finaNvoice, req.getParameterMap());
		 Page<FinaNvoice> page = new Page<FinaNvoice>(pageNo, pageSize);
		 queryWrapper.eq("type","1");
		 queryWrapper.orderByDesc("create_time");
		 IPage<FinaNvoice> pageList = finaNvoiceService.page(page, queryWrapper);
		 for (FinaNvoice nvoice : pageList.getRecords()) {
			 String rate = "0%";
			 if(oConvertUtils.isNotEmpty(nvoice.getTaxRate())) {
				 rate = nvoice.getTaxRate();
			 }
//			 获取税率
			 String[] str=rate.split("%");
//			 计算税额
			 BigDecimal tax=new BigDecimal(str[0]).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
			 BigDecimal taxAmount=nvoice.getInvoicePrice().multiply(tax);
			 nvoice.setTaxAmount(taxAmount);//税额
			 nvoice.setNoTaxPrice(nvoice.getInvoicePrice().subtract(taxAmount));//无税金额
			 nvoice.setTaxPrice(nvoice.getInvoicePrice());//含税金额
		 }
		 return Result.ok(pageList);
	 }

	 /**
	  * 分页列表查询
	  *
	  * @param finaNvoice
	  * @return
	  */
	 @AutoLog(value = "收款发票表单-发票合计")
	 @ApiOperation(value="收款发票-发票合计", notes="收款发票-发票合计")
	 @GetMapping(value = "/sumPriceSK")
	 public Result<?> sumPriceSK(FinaNvoiceSumPrice finaNvoice ) {
		 FinaNvoiceSumPrice nvoiceSumPrice = finaNvoiceService.getInvoiceSumPrice("1",finaNvoice.getCustomerName()
		 								,finaNvoice.getInvoiceTime_begin(),finaNvoice.getInvoiceTime_end());
		 return Result.ok(nvoiceSumPrice);
	 }



	 /**
	  * 分页列表查询
	  *
	  * @param finaNvoice
	  * @return
	  */
	 @AutoLog(value = "收款发票表单-发票合计")
	 @ApiOperation(value="收款发票-发票合计", notes="收款发票-发票合计")
	 @GetMapping(value = "/sumPriceFK")
	 public Result<?> sumPriceFK(FinaNvoiceSumPrice finaNvoice ) {
		 FinaNvoiceSumPrice nvoiceSumPrice = finaNvoiceService.getInvoiceSumPrice("0",finaNvoice.getSupplierName()
				 ,finaNvoice.getInvoiceTime_begin(),finaNvoice.getInvoiceTime_end());
		 return Result.ok(nvoiceSumPrice);
	 }



	/**
	 *   添加
	 *
	 * @param finaNvoice
	 * @return
	 */
	@AutoLog(value = "发票表单-添加开票信息")
	@ApiOperation(value="发票表单-添加开票信息", notes="发票表单-添加开票信息")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FinaNvoice finaNvoice) {
		if(finaNvoice.getNvoiceType().equals(1)){
			//收款
			BasCustomer basCustomer=customerService.getById(finaNvoice.getCustomerId());
			if(basCustomer!=null){
				finaNvoice.setCustomerName(basCustomer.getName());
			}
		}else{
			//付款
			BasSupplier basSupplier=supplierService.getById(finaNvoice.getSupplierId());
			if(basSupplier!=null){
				finaNvoice.setSupplierName(basSupplier.getName());
			}
		}
		finaNvoiceService.save(finaNvoice);
		if(StringUtils.isNotBlank(finaNvoice.getCustomerId())){
			//收款
			finaNvoiceService.addInvoiceOrReceipt(finaNvoice);
		}else{
			//付款

		}
		return Result.ok("添加成功！");
	}

	 /**
	  *   添加
	  *
	  * @param finaNvoice
	  * @return
	  */
	 @AutoLog(value = "发票表单-添加付款开票信息")
	 @ApiOperation(value="发票表单-添加付款开票信息", notes="发票表单-添加付款开票信息")
	 @PostMapping(value = "/addFK")
	 public Result<?> addFK(@RequestBody FinaNvoice finaNvoice) {
		 //付款
		 BasSupplier basSupplier = supplierService.getById(finaNvoice.getSupplierId());
		 if (basSupplier != null) {
			 finaNvoice.setSupplierName(basSupplier.getName());
		 }
		 finaNvoice.setActualAmount(finaNvoice.getInvoicePrice());
		 finaNvoice.setType("0");
		 LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
		 TaxRate taxRate=taxRateService.getOne(wrapper);
		if(taxRate!=null){
			finaNvoice.setTaxRate(taxRate.getTaxRate());
		}
		 finaNvoiceService.addInvoiceOrFK(finaNvoice);
		 return Result.ok("添加成功！");
	 }

	 /**
	  *   添加
	  *
	  * @param finaNvoice
	  * @return
	  */
	 @AutoLog(value = "发票表单-添加收款开票信息")
	 @ApiOperation(value="发票表单-添加收款开票信息", notes="发票表单-添加收款开票信息")
	 @PostMapping(value = "/addSK")
	 public Result<?> addSK(@RequestBody FinaNvoice finaNvoice) {
		 //收款
		 BasCustomer basCustomer = customerService.getById(finaNvoice.getCustomerId());
		 if (basCustomer != null) {
			 finaNvoice.setCustomerName(basCustomer.getName());
			 finaNvoice.setCustomerId(basCustomer.getId());
		 }
		 finaNvoice.setActualAmount(finaNvoice.getInvoicePrice());
		 finaNvoice.setType("1");
		 LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
		 TaxRate taxRate=taxRateService.getOne(wrapper);
		 if(taxRate!=null){
			 finaNvoice.setTaxRate(taxRate.getTaxRate());
		 }
		 finaNvoiceService.addInvoiceOrReceipt(finaNvoice);
		 return Result.ok("添加成功！");
	 }


	/**
	 *  销售开票编辑
	 *
	 * @param finaNvoice
	 * @return
	 */
	@AutoLog(value = "发票表单-编辑")
	@ApiOperation(value="发票表单-编辑", notes="发票表单-编辑")
	@PutMapping(value = "/editSK")
	public Result<?> editSK(@RequestBody FinaNvoice finaNvoice) {
		finaNvoice.setActualAmount(finaNvoice.getInvoicePrice());
		LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
		 TaxRate taxRate=taxRateService.getOne(wrapper);
		 if(taxRate!=null){
			 finaNvoice.setTaxRate(taxRate.getTaxRate());
		 }
		finaNvoiceService.updateInvoiceOrReceipt(finaNvoice);
		return Result.ok("编辑成功!");
	}
	
	
	/**
	 *  进货开票编辑
	 *
	 * @param finaNvoice
	 * @return
	 */
	@AutoLog(value = "进货开票表单-编辑")
	@ApiOperation(value="进货开票表单-编辑", notes="进货开票表单-编辑")
	@PutMapping(value = "/editFK")
	public Result<?> editFK(@RequestBody FinaNvoice finaNvoice) {
		finaNvoice.setActualAmount(finaNvoice.getInvoicePrice());
		LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
		 TaxRate taxRate=taxRateService.getOne(wrapper);
		 if(taxRate!=null){
			 finaNvoice.setTaxRate(taxRate.getTaxRate());
		 }
		finaNvoiceService.updateInvoiceOrPayment(finaNvoice);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "发票表单-通过id删除")
	@ApiOperation(value="发票表单-通过id删除", notes="发票表单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		finaNvoiceService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  销售开票批量删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销售开票批量删除")
	@ApiOperation(value="销售开票批量删除", notes="销售开票批量删除")
	@DeleteMapping(value = "/deleteSK")
	public Result<?> deleteSK(@RequestParam(name="id",required=true) String id) {
		this.finaNvoiceService.deleteBatchSK(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  进货开票批量删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进货开票批量删除")
	@ApiOperation(value="进货开票批量删除", notes="进货开票批量删除")
	@DeleteMapping(value = "/deleteFK")
	public Result<?> deleteFK(@RequestParam(name="id",required=true) String id) {
		this.finaNvoiceService.deleteBatchFK(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "发票表单-通过id查询")
	@ApiOperation(value="发票表单-通过id查询", notes="发票表单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FinaNvoice finaNvoice = finaNvoiceService.getById(id);
		if(finaNvoice==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(finaNvoice);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param finaNvoice
    */
    @RequestMapping(value = "/exportXlsSK")
    public ModelAndView exportXlsSK(HttpServletRequest request, FinaNvoice finaNvoice) {
    	finaNvoice.setType("1");
		// Step.1 组装查询条件
		QueryWrapper<FinaNvoice> queryWrapper = QueryGenerator.initQueryWrapper(finaNvoice, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<FinaNvoice> pageList = finaNvoiceService.list(queryWrapper);
		List<FinaNvoice> exportModelList = null;
		List<FinaNvoiceSKVO> exportList = Lists.newArrayList();
		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportModelList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		} else {
			exportModelList = pageList;
		}
		exportList = convertList2List(exportModelList,FinaNvoiceSKVO.class);
		for (FinaNvoiceSKVO nvoice : exportList) {
			String rate = "0%";
			if(oConvertUtils.isNotEmpty(nvoice.getTaxRate())) {
				rate = nvoice.getTaxRate();
			}
//			 获取税率
			String[] str=rate.split("%");
//			 计算税额
			BigDecimal tax=new BigDecimal(str[0]).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
			BigDecimal taxAmount=nvoice.getInvoicePrice().multiply(tax);
			nvoice.setTaxAmount(taxAmount);//税额
			nvoice.setNoTaxPrice(nvoice.getInvoicePrice().subtract(taxAmount));//无税金额
			nvoice.setTaxPrice(nvoice.getInvoicePrice());//含税金额
		}
		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "销售发票"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, FinaNvoiceSKVO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("销售发票" + "报表", "导出人:" + sysUser.getRealname(), "销售发票"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
    }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param finaNvoice
	  */
	 @RequestMapping(value = "/exportXlsFK")
	 public ModelAndView exportXlsFK(HttpServletRequest request, FinaNvoice finaNvoice) {
		 finaNvoice.setType("0");
		 // Step.1 组装查询条件
		 QueryWrapper<FinaNvoice> queryWrapper = QueryGenerator.initQueryWrapper(finaNvoice, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<FinaNvoice> pageList = finaNvoiceService.list(queryWrapper);
		 List<FinaNvoice> exportModelList = null;
		 List<FinaNvoiceFKVO> exportList = Lists.newArrayList();
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportModelList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		 } else {
			 exportModelList = pageList;
		 }
		 exportList = convertList2List(exportModelList,FinaNvoiceFKVO.class);
		 for (FinaNvoiceFKVO nvoice : exportList) {
			 String rate = "0%";
			 if(oConvertUtils.isNotEmpty(nvoice.getTaxRate())) {
				 rate = nvoice.getTaxRate();
			 }
//			 获取税率
			 String[] str=rate.split("%");
//			 计算税额
			 BigDecimal tax=new BigDecimal(str[0]).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
			 BigDecimal taxAmount=nvoice.getInvoicePrice().multiply(tax);
			 nvoice.setTaxAmount(taxAmount);//税额
			 nvoice.setNoTaxPrice(nvoice.getInvoicePrice().subtract(taxAmount));//无税金额
			 nvoice.setTaxPrice(nvoice.getInvoicePrice());//含税金额
		 }
		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "进货发票"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, FinaNvoiceFKVO.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("进货发票" + "报表", "导出人:" + sysUser.getRealname(), "进货发票"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FinaNvoice.class);
    }

	 /**
	  * 收款发票excel导入模板
	  *
	  * @param request
	  * @param finaNvoiceDto
	  * @return
	  */
	 @RequestMapping(value = "/importExcelTemplate")
	 public ModelAndView importExcelTemplate(HttpServletRequest request, FinaNvoiceDto finaNvoiceDto) {
		 return importExcelsTemplate(request, finaNvoiceDto, FinaNvoiceDto.class, "开票信息");
	 }

	 private ModelAndView importExcelsTemplate(HttpServletRequest request, FinaNvoiceDto finaNvoiceDto, Class<FinaNvoiceDto> clazz, String title) {

		 // Step.1 获取导出数据
		 List<FinaNvoiceDto> pageList = Lists.newArrayList();
		 FinaNvoiceDto  nvoiceDto=new FinaNvoiceDto();
		 nvoiceDto.setCustomerName("潍坊启元胶粘制品有限公司");
		 nvoiceDto.setInvoiceNo("202104013321");
		 nvoiceDto.setInvoiceTime(new Date());
		 nvoiceDto.setRemark("青岛即墨大圣");
		 nvoiceDto.setNvoiceType("增值税专用发票(请填写完整名称)");
		 nvoiceDto.setInvoicePrice(new BigDecimal("2000.22113").setScale(4, BigDecimal.ROUND_HALF_UP));
		 pageList.add(nvoiceDto);

		 // Step.2 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, clazz);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "销售发票模板", "", title));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }



	 /**
	  * 付款excel导入模板
	  *
	  * @param request
	  * @param finaNvoiceDto
	  * @return
	  */
	 @RequestMapping(value = "/importExcelTemplateFK")
	 public ModelAndView importExcelTemplateFK(HttpServletRequest request, FinaNvoiceDto finaNvoiceDto) {
		 return importExcelsTemplateFK(request, FinaNvoiceFKDto.class, "开票信息");
	 }

	 private ModelAndView importExcelsTemplateFK(HttpServletRequest request, Class<FinaNvoiceFKDto> clazz, String title) {

		 // Step.1 获取导出数据
		 List<FinaNvoiceFKDto> pageList = Lists.newArrayList();
		 FinaNvoiceFKDto  nvoiceDto=new FinaNvoiceFKDto();
		 nvoiceDto.setSupplierName("上海金大科技有限公司");
		 nvoiceDto.setInvoiceNo("202104013321");
		 nvoiceDto.setInvoiceTime(new Date());
		 nvoiceDto.setRemark("芬欧汇川（中国）有限公司");
		 nvoiceDto.setNvoiceType("增值税专用发票(请填写完整名称)");
		 nvoiceDto.setInvoicePrice(new BigDecimal("2000.22113").setScale(4, BigDecimal.ROUND_HALF_UP));
		 pageList.add(nvoiceDto);

		 // Step.2 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, clazz);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "进货发票模板", "", title));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }


 	/**
      * 补充导入发票（开票）信息
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcelReplenish", method = RequestMethod.POST)
    public Result<?> importExcelPart(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		List<String> noList = finaNvoiceMapper.selectAllNvoiceNo();//查询所有票号（用于筛选重复票号）
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
			TaxRate taxRate = null;
			taxRate=taxRateService.getOne(wrapper);
			String tax="";
			if(taxRate!=null){
				tax=taxRate.getTaxRate();
			}
			try {
				List<FinaNvoice> nvoiceList = finaNvoiceService.selectNvoiceByNoOrPrice("1");
				List<FinaNvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), FinaNvoice.class, params);
				List<FinaNvoice> fList = Lists.newArrayList();
				List<String> codeList = Lists.newArrayList();
				if(list !=null && list.size()>0) {
					for (FinaNvoice finaNvoice : list) {
						if (!noList.contains(finaNvoice.getInvoiceNo())
								&&!codeList.contains(finaNvoice.getInvoiceNo())
								&&nvoiceList!=null&&nvoiceList.size()>0) {
							for (FinaNvoice nvoice : nvoiceList) {
								if (StringUtils.equals(finaNvoice.getCustomerName().trim(), nvoice.getCustomerName()) &&
										finaNvoice.getTaxPrice().compareTo(nvoice.getInvoicePrice())==0) {
									nvoice.setInvoiceNo(finaNvoice.getInvoiceNo());
									nvoice.setInvoiceTime(finaNvoice.getInvoiceTime());
									String type="";
									if(oConvertUtils.isNotEmpty(finaNvoice.getNvoiceType())){
										type=baseAPI.queryDictKeyByValue(finaNvoice.getNvoiceType().toString());
										if(oConvertUtils.isNotEmpty(type)) {
											nvoice.setNvoiceType(type);
										}
									}
									nvoice.setTaxRate(tax);
//									nvoice.setInvoicePrice(finaNvoice.getTaxPrice());//模板叫含税金额，即开票金额
									
									LambdaQueryWrapper<BasCustomer> queryWrapper = new LambdaQueryWrapper<BasCustomer>();
									 queryWrapper.eq(BasCustomer::getName, finaNvoice.getCustomerName().trim());
									 BasCustomer customer = customerService.getOne(queryWrapper);
									 if(customer!=null) {
//										 nvoice.setCustomerName(customer.getName());
//										 nvoice.setCustomerId(customer.getId());
										 fList.add(nvoice);
									 }
								}
							}
						}
						codeList.add(finaNvoice.getInvoiceNo());
					}
				}
				
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();
				finaNvoiceService.updateBatchById(fList);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + fList.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}



	 /**
	  * 补充导入发票信息
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value = "/importExcelFK", method = RequestMethod.POST)
	 public Result<?> importExcelPartFK(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 List<String> noList = finaNvoiceMapper.selectAllNvoiceNo();//查询所有票号（用于筛选重复票号）
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
			 TaxRate taxRate=taxRateService.getOne(wrapper);
			 String tax="";
			 if(taxRate!=null){
				 tax=taxRate.getTaxRate();
			 }
			 try {
				 List<FinaNvoice> nvoiceList = finaNvoiceService.selectNvoiceByNoOrPrice("0");
				 List<FinaNvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), FinaNvoice.class, params);
				 List<FinaNvoice> fList = Lists.newArrayList();
				 List<String> codeList = Lists.newArrayList();
				 if(list !=null && list.size()>0) {
					 for (FinaNvoice finaNvoice : list) {
						 if (!noList.contains(finaNvoice.getInvoiceNo())
									&&!codeList.contains(finaNvoice.getInvoiceNo())
									&&nvoiceList!=null&&nvoiceList.size()>0) {
							 for (FinaNvoice nvoice : nvoiceList) {
								 if (finaNvoice.getSupplierName().equals(nvoice.getSupplierName()) &&
										 finaNvoice.getTaxPrice().equals(nvoice.getInvoicePrice())) {
									 nvoice.setInvoiceNo(finaNvoice.getInvoiceNo());
									 nvoice.setInvoiceTime(finaNvoice.getInvoiceTime());
									 String type="";
									 if(oConvertUtils.isNotEmpty(finaNvoice.getNvoiceType())){
										 type=baseAPI.queryDictKeyByValue(finaNvoice.getNvoiceType().toString());
										 nvoice.setNvoiceType(type);
									 }
									 nvoice.setTaxRate(tax);
									 fList.add(nvoice);
//									 nvoice.setInvoicePrice(finaNvoice.getTaxAmount());
//									 nvoice.setSupplierName(finaNvoice.getSupplierName());
								 }
							 }
						 }
						 codeList.add(finaNvoice.getInvoiceNo());
					 }
				 }
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();
				 finaNvoiceService.updateBatchById(fList);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 return Result.ok("文件导入成功！数据行数：" + fList.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }



	/**
      * 通过excel导入数据--销售开票
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public Result<?> importExcelReplenish(HttpServletRequest request, HttpServletResponse response) {
        return importExcels(request, response, FinaNvoice.class);
    }

	 protected Result<?> importExcels(HttpServletRequest request, HttpServletResponse response, Class<FinaNvoice> clazz) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 List<String> finaNvoiceNoList = finaNvoiceMapper.selectAllNvoiceNo();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
//			 LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
			 TaxRate taxRate=taxRateService.list().get(0);
			 String tax="";
			 if(taxRate!=null){
				 tax=taxRate.getTaxRate();
			 }
			 try {
				 int size = 0;
				 List<FinaNvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
				 List<String> codeList = Lists.newArrayList();
				 StringBuffer buffer = new StringBuffer();
//				 List<FinaNvoice> fList = Lists.newArrayList();
				 for (FinaNvoice finaNvoice : list) {
					 String customerName = "";
					 if(oConvertUtils.isNotEmpty(finaNvoice.getCustomerName())) {
						 customerName = finaNvoice.getCustomerName().trim();
						 LambdaQueryWrapper<BasCustomer> queryWrapper = new LambdaQueryWrapper<BasCustomer>();
						 queryWrapper.eq(BasCustomer::getName, customerName);
						 BasCustomer customer = null;
						 try {
							 customer = customerService.getOne(queryWrapper);
						 }catch (Exception e) {
							throw new RuntimeException("查到重名客户是：" + customerName);
						}
						 if(customer!=null) {
							 finaNvoice.setType("1");
							 if(oConvertUtils.isNotEmpty(finaNvoice.getNvoiceType())){
								String invoiceType=baseAPI.queryDictKeyByValue(finaNvoice.getNvoiceType());
								finaNvoice.setNvoiceType(invoiceType);
							 }
							 finaNvoice.setTaxRate(tax);
							 finaNvoice.setInvoicePrice(finaNvoice.getTaxPrice());
							 finaNvoice.setActualAmount(finaNvoice.getTaxPrice());
							 finaNvoice.setCustomerId(customer.getId());
							 finaNvoice.setCustomerName(customer.getName());
							//添加发票金额到收款表
							 if(finaNvoiceNoList.contains(finaNvoice.getInvoiceNo())
									 ||codeList.contains(finaNvoice.getInvoiceNo())
									 ||oConvertUtils.isEmpty(finaNvoice.getTaxPrice())) {
								 buffer.append(finaNvoice.getCustomerName());
								 buffer.append(",");
							 }else {
								 size++;
								 finaNvoiceService.addInvoiceOrReceipt(finaNvoice);
//								 fList.add(finaNvoice);
							 }
						 }else {
							 buffer.append(finaNvoice.getCustomerName());
							 buffer.append(",");
						 }
					 }
					 codeList.add(finaNvoice.getInvoiceNo());
				 }
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();
//				 finaNvoiceService.saveBatch(fList);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 if(buffer != null && buffer.length()>0) {
					 buffer.insert(0, "未导入成功客户：");
					 return Result.ok(buffer.toString());
				 }
				 return Result.ok("文件导入成功！数据行数：" + size);
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }
	 
	 
	 /**
      * 通过excel导入数据--进货开票
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcelReFK", method = RequestMethod.POST)
    public Result<?> importExcelReFK(HttpServletRequest request, HttpServletResponse response) {
        return importExcelsFK(request, response, FinaNvoice.class);
    }

	 protected Result<?> importExcelsFK(HttpServletRequest request, HttpServletResponse response, Class<FinaNvoice> clazz) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 List<String> finaNvoiceNoList = finaNvoiceMapper.selectAllNvoiceNo();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
//			 LambdaQueryWrapper<TaxRate> wrapper=new LambdaQueryWrapper<>();
			 TaxRate taxRate=taxRateService.list().get(0);
			 String tax="";
			 if(taxRate!=null){
				 tax=taxRate.getTaxRate();
			 }
			 try {
				 int size = 0;
				 List<FinaNvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
				 List<String> codeList = Lists.newArrayList();
				 StringBuffer buffer = new StringBuffer();
//				 List<FinaNvoice> fList = Lists.newArrayList();
				 for (FinaNvoice finaNvoice : list) {
					 String supplierName = "";
					 if(oConvertUtils.isNotEmpty(finaNvoice.getSupplierName())) {
						 supplierName = finaNvoice.getSupplierName().trim();
						 LambdaQueryWrapper<BasSupplier> queryWrapper = new LambdaQueryWrapper<BasSupplier>();
						 queryWrapper.eq(BasSupplier::getName, supplierName);
						 BasSupplier supplier = null;
						 try {
							 supplier = supplierService.getOne(queryWrapper);
						 }catch (Exception e) {
							throw new RuntimeException("查到重名供应商是：" + supplierName);
						}
						 if(supplier!=null) {
							 finaNvoice.setType("0");
							 if(oConvertUtils.isNotEmpty(finaNvoice.getNvoiceType())){
								String invoiceType=baseAPI.queryDictKeyByValue(finaNvoice.getNvoiceType());
								 finaNvoice.setNvoiceType(invoiceType);
							 }
							 finaNvoice.setTaxRate(tax);
							 finaNvoice.setInvoicePrice(finaNvoice.getTaxPrice());
							 finaNvoice.setActualAmount(finaNvoice.getTaxPrice());
							 finaNvoice.setSupplierId(supplier.getId());
							 finaNvoice.setSupplierName(supplier.getName());
							//添加发票金额到收款表
							 if(finaNvoiceNoList.contains(finaNvoice.getInvoiceNo())
									 ||codeList.contains(finaNvoice.getInvoiceNo())
									 ||oConvertUtils.isEmpty(finaNvoice.getTaxPrice()))  {
								 buffer.append(finaNvoice.getSupplierName());
								 buffer.append(",");
							 }else {
								 size++;
								 finaNvoiceService.addInvoiceOrFK(finaNvoice);
//								 fList.add(finaNvoice);
							 }
						 }else {
							 buffer.append(finaNvoice.getSupplierName());
							 buffer.append(",");
						 }
					 }
					 codeList.add(finaNvoice.getInvoiceNo());
				 }
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();
//				 finaNvoiceService.saveBatch(fList);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 if(buffer != null && buffer.length()>0) {
					 buffer.insert(0, "未导入成功供应商：");
					 return Result.ok(buffer.toString());
				 }
				 return Result.ok("文件导入成功！数据行数：" + size);
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

	 /**
	  * 获取对象ID
	  *
	  * @return
	  */
	 private String getId(FinaNvoice item) {
		 try {
			 return PropertyUtils.getProperty(item, "id").toString();
		 } catch (Exception e) {
			 e.printStackTrace();
			 return null;
		 }
	 }

	 /**
	  * @param input 输入集合
	  * @param clzz  输出集合类型
	  * @param <E>   输入集合类型
	  * @param <T>   输出集合类型
	  * @return 返回集合
	  */
	 public static <E, T> List<T> convertList2List(List<E> input, Class<T> clzz) {
		 List<T> output = Lists.newArrayList();
		 if (CollectionUtils.isNotEmpty(input)) {
			 for (E source : input) {
				 T target = BeanUtils.instantiate(clzz);
				 BeanUtil.copyProperties(source, target);
				 output.add(target);
			 }
		 }
		 return output;
	 }

}
